package com.promise.jokerdream.response.parser

import com.promise.jokerdream.response.phone.FactionBossData
import com.promise.jokerdream.response.phone.FactionFriendData
import com.promise.jokerdream.response.phone.FactionFriendXmlResponse
import org.jsoup.Jsoup

/**
 * 帮友XML解析器
 * 专门用于解析大乐斗帮友相关的XML数据
 * 基于Jsoup实现
 */
class FactionFriendXmlParser : BaseXmlParser<FactionFriendXmlResponse>() {
    
    /**
     * 解析帮友XML数据
     * @param xmlString XML字符串
     * @return 解析结果
     */
    fun parseFactionFriendXml(xmlString: String): XmlParseResult<FactionFriendXmlResponse> {
        return parseXml(xmlString)
    }
    
    /**
     * 实现基类的具体解析逻辑
     * @param xmlString XML字符串
     * @return 解析后的帮友数据
     */
    override fun doParse(xmlString: String): FactionFriendXmlResponse {
        val extractedData = mutableMapOf<String, Any>()
        
        try {
            val doc = Jsoup.parse(xmlString)
            val divElement = doc.selectFirst("div#id")
            
            if (divElement != null) {
                val html = divElement.html()
                parseDivContent(html, extractedData)
            }
        } catch (e: Exception) {
            // 解析失败，返回空数据
        }
        
        return FactionFriendXmlResponse(
            actionResult = extractedData["actionResult"] as? String ?: "",
            currentVitality = extractedData["vitality"] as? String ?: "0/100",
            factionBossList = extractedData["factionBossList"] as? List<FactionBossData> ?: emptyList(),
            factionFriendList = extractedData["factionFriendList"] as? List<FactionFriendData> ?: emptyList(),
            currentPage = extractedData["currentPage"] as? Int ?: 1,
            totalPages = extractedData["totalPages"] as? Int ?: 1
        )
    }
    
    /**
     * 解析div内容
     */
    private fun parseDivContent(html: String, data: MutableMap<String, Any>) {
        // 统一替换<br />为<br/>，确保Jsoup能正确识别
        val normalizedHtml = html.replace(Regex("<br\\s*/?>"), "<br/>")
        val doc = Jsoup.parse(normalizedHtml)
        val divElement = doc.selectFirst("div#id")
        
        // 提取体力值
        val vitalityRegex = Regex("当前体力值：([^\\s]+)")
        val vitalityMatch = vitalityRegex.find(html)
        if (vitalityMatch != null) {
            data["vitality"] = vitalityMatch.groupValues[1]
        }
        
        // 提取分页信息
        val pageRegex = Regex("第(\\d+)/(\\d+)页")
        val pageMatch = pageRegex.find(html)
        if (pageMatch != null) {
            data["currentPage"] = pageMatch.groupValues[1].toInt()
            data["totalPages"] = pageMatch.groupValues[2].toInt()
        }
        
        // 解析boss数据（侠）
        val factionBossList = mutableListOf<FactionBossData>()
        // 解析帮友数据（帮主、副帮主、护法等）
        val factionFriendList = mutableListOf<FactionFriendData>()

        // 按行分割内容
        val lines = normalizedHtml.split("<br/>")
        for (line in lines) {
            val trimmedLine = line.trim()
            if (trimmedLine.isEmpty()) continue
            
            // 解析侠数据
            if (trimmedLine.contains("侠：")) {
                val factionBossData = parseFactionBossData(trimmedLine)
                if (factionBossData != null) {
                    factionBossList.add(factionBossData)
                }
            }
            // 解析帮主、副帮主、护法、长老、堂主、精英、帮众
            else if (trimmedLine.contains("帮：") || trimmedLine.contains("副：") || 
                trimmedLine.contains("护：") || trimmedLine.contains("长：") || 
                trimmedLine.contains("堂：") || trimmedLine.contains("精：") || 
                trimmedLine.contains("众：")) {
                val factionFriendData = parseFactionFriendData(trimmedLine)
                if (factionFriendData != null) {
                    factionFriendList.add(factionFriendData)
                }
            }
        }
        
        data["factionBossList"] = factionBossList
        data["factionFriendList"] = factionFriendList
    }
    
    /**
     * 解析boss数据（侠）
     */
    private fun parseFactionBossData(lineText: String): FactionBossData? {
        return try {
            // 匹配名称链接
            val nameRegex = Regex("侠：.*?<a[^>]*>([^<]+)</a>")
            val levelRegex = Regex("</a>\\s*(\\d+)级\\s*")
            val uidRegex = Regex("B_UID=(\\d+)")
            val fightUrlRegex = Regex("<a[^>]*href=\"([^\"]*fight[^\"]*)\"[^>]*>")
            val isFoughtRegex = Regex("已乐斗")
            
            val nameMatch = nameRegex.find(lineText)
            val levelMatch = levelRegex.find(lineText)
            val uidMatch = uidRegex.find(lineText)
            val fightUrlMatch = fightUrlRegex.find(lineText)
            val isFought = isFoughtRegex.containsMatchIn(lineText)
            
            if (nameMatch != null && levelMatch != null && uidMatch != null && fightUrlMatch != null) {
                FactionBossData(
                    name = nameMatch.groupValues[1].replace("&nbsp;", "").trim(),
                    level = levelMatch.groupValues[1].toInt(),
                    uid = uidMatch.groupValues[1],
                    fightUrl = fightUrlMatch.groupValues[1],
                    isFought = isFought
                )
            } else {
                null
            }
        } catch (e: Exception) {
            null
        }
    }
    
    /**
     * 解析帮友数据
     */
    private fun parseFactionFriendData(lineText: String): FactionFriendData? {
        return try {
            // 匹配职位前缀：帮、副、护、长、堂、精、众
            val positionRegex = Regex("(帮|副|护|长|堂|精|众)：")
            val positionMatch = positionRegex.find(lineText)
            val position = positionMatch?.groupValues?.get(1) ?: ""
            
            // 匹配名称链接
            val nameRegex = Regex("<a[^>]*>([^<]+)</a>")
            val levelRegex = Regex("(\\d+)级\\s*")
            val factionRegex = Regex("级\\s*([^\\s<]+)")
            val uidRegex = Regex("B_UID=(\\d+)")
            val fightUrlRegex = Regex("<a[^>]*href=\"([^\"]*fight[^\"]*)\"[^>]*>")
            val isFoughtRegex = Regex("已乐斗")
            val specialSkillRegex = Regex("神拳")
            
            val nameMatch = nameRegex.find(lineText)
            val levelMatch = levelRegex.find(lineText)
            val factionMatch = factionRegex.find(lineText)
            val uidMatch = uidRegex.find(lineText)
            val fightUrlMatch = fightUrlRegex.find(lineText)
            val isFought = isFoughtRegex.containsMatchIn(lineText)
            val specialSkill = specialSkillRegex.find(lineText)?.value
            
            if (nameMatch != null && levelMatch != null && uidMatch != null && fightUrlMatch != null) {
                FactionFriendData(
                    name = nameMatch.groupValues[1].replace("&nbsp;", "").trim(),
                    level = levelMatch.groupValues[1].toInt(),
                    uid = uidMatch.groupValues[1],
                    faction = factionMatch?.groupValues?.get(1) ?: "",
                    fightUrl = fightUrlMatch.groupValues[1],
                    isFought = isFought,
                    specialSkill = specialSkill
                )
            } else {
                null
            }
        } catch (e: Exception) {
            null
        }
    }
}
